import count from '@dfeidao/atom-nodejs/db/count';
import query from '@dfeidao/atom-nodejs/db/query';


interface Message {
	filter: { productid: {}, usercode: {}; $and: Array<{}> };
	sort: {};
	page_size: number;
	page_no: number;
	productid: string;
	repeat: string;
}

export default async function atom(msg: Message, action_id: string, session_id: string, spaceid: string) {
	const systemid = '12';
	const { exec, prepare } = query(action_id, session_id, systemid);
	const asc: string[] = [];
	const desc: string[] = [];
	if (msg.sort) {
		const key = Object.keys(msg.sort)[0];
		if (parseInt(msg.sort[key], 10) === -1) {
			desc.push(key);
		} else {
			asc.push(key);
		}
	}
	if (!asc[0]) {
		asc.splice(0, 1);
	}
	const filter = msg.filter;
	if (msg.repeat) {
		filter.productid = { $in: [msg.productid] };
	} else {
		if (filter.usercode) {
			filter.productid = { $in: [msg.productid] };
			filter.$and = [{ usercode: { $ne: "admin" } }, { usercode: filter.usercode }];
			delete filter.usercode;
		} else {
			filter.productid = { $in: [msg.productid] };
			filter.usercode = { $ne: 'admin' };
		}
	}

	prepare('pub_user', ['_id', 'usercode', 'user_name', 'is_disabled', 'productid', 'avatar_path', 'avatar_name', 'avatar_type', 'email', 'name_spell', 'phone', 'password', 'last_login_time', 'phone_verified'], filter, msg.page_size, msg.page_no, asc, desc);
	const [data] = await exec();

	const c = count(action_id, session_id, systemid);
	c.prepare('pub_user', filter);
	const [t] = await c.exec();
	return { dataArray: data, count: t };
}
